package com.nut.util;

import com.nut.common.RedisKeys;
import com.nut.enums.OrderTagEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@Component
public class IdUtil {

    public static final String DATE_YYMMDDHHMMSS = "yyMMddHHmmss";
    public static final String TEST = "test";
    public static final String DIGIT6 = "%06d";
    public static final String DIGIT5 = "%05d";

    public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(DATE_YYMMDDHHMMSS);

    public static Long getMemberId() {
        String str = FORMATTER.format(LocalDateTime.now()) + (10 + ThreadLocalRandom.current().nextInt(89));
        return Long.valueOf(str);
    }

    /**
     * 生成Id   yyMMdd+ 00001(一天可生成10W个ID) + 90（订单标识）
     * 长度 6+2+5 = 13
     *
     * @param orderTagEnum
     * @return
     */
    public static Long generatedCommonId(OrderTagEnum orderTagEnum) {
        String prefix = RedisKeys.getPrefixKey(orderTagEnum);

        RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate", RedisTemplate.class);
        Long increment = redisTemplate.opsForValue().increment(prefix);
        // 对KEY添加过期时间
        redisTemplate.opsForValue().set(prefix, increment, 3, TimeUnit.DAYS);

        StringBuilder sb = new StringBuilder();
        sb.append(prefix);
        //最多10W比订单
        if (increment.toString().length() < 5) {
            sb.append(String.format(DIGIT5, increment));
        } else {
            sb.append(increment);
        }
        return Long.valueOf(sb.toString());
    }

    public static String generateSsn() {
        int random = ThreadLocalRandom.current().nextInt(100);
        StringBuilder sb = new StringBuilder();
        sb.append(System.currentTimeMillis());
        if (random < 10) {
            sb.append("0" + random);
        } else {
            sb.append(random);
        }

        return sb.toString();
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static void main(String[] args) {
    }


}
